
package dk.unet.android.data;

import dk.unet.android.data.queries.DeleteQuery;
import dk.unet.android.data.queries.WhereClasses;
import dk.unet.android.data.queries.SelectQuery;
import dk.unet.android.data.queries.Query;
import dk.unet.android.data.queries.InsertQuery;
import dk.unet.android.data.queries.UpdateQuery;
import dk.unet.android.data.queries.ValueQuery;
import dk.unet.android.data.queries.WhereQuery;

/**
 *
 * @author jesperjansen
 */
public class QueryBuilder {
    private Query query;

    private QueryBuilder(){}

    public QueryBuilder from(String table){
        query.setTable(table);
        return this;
    }

    public QueryBuilder into(String table){
        return this.from(table);
    }

    /**
     * Remeber theese are string, and goes directly into the database.
     * So escape strings and check your numbers
     * @param values
     * @return
     */
    public QueryBuilder values(String... values){
        if(this.query instanceof ValueQuery){
            ((ValueQuery)this.query).setValues(values);
        }
        return this;
    }

    /**
     * If the right hand side of the query is different from a numeric value
     * it is treated as a string, and therefore enclosed in quotes
     * @param left typically the fields to check
     * @param op Operator to use when testing
     * @param right the value the left side is matched to with op
     * @return
     */
    public QueryBuilder where(String left, WhereClasses op, Object right){
        if(!(this.query instanceof WhereQuery)){
            WhereQuery q = (WhereQuery)this.query;
            String rightSide = "";

            if(right instanceof Number){
                rightSide = right.toString();
            }else{
                rightSide = "\""+right.toString()+"\"";
            }

            String clause = left + op.operator() + rightSide;

            q.addWhere(clause);
        }
        return this;
    }

    public Query build(){
        return this.query;
    }

    public static QueryBuilder select(String... fields)
    {
        QueryBuilder qb = new QueryBuilder();
        
        qb.query = new SelectQuery();
        qb.query.setFields(fields);

        return qb;
    }
    public static QueryBuilder insert(String... fields)
    {
        QueryBuilder qb = new QueryBuilder();

        qb.query = new InsertQuery();
        qb.query.setFields(fields);

        return qb;
    }
    public static QueryBuilder update(String... fields)
    {
        QueryBuilder qb = new QueryBuilder();
        qb.query = new UpdateQuery();
        qb.query.setFields(fields);
        
        return qb;
    }
    public static QueryBuilder delete(String tableName)
    {
        QueryBuilder qb = new QueryBuilder();
        qb.query = new DeleteQuery();
        qb.query.setTable(tableName);

        return qb;
    }
}
